<?php

namespace maotool\lock;

use maotool\core\facade\Config;
use maotool\file\DirUtil;
use maotool\file\FileUtil;
use maotool\util\PathUtil;

class FileLock implements Lock
{

    public function create($key)
    {
        $path = Config::get("framework.runtime.lock.path");
        $dirPath = PathUtil::path($path, substr(md5($key), 0, 2));
        if (DirUtil::notExist($dirPath)) {
            DirUtil::create($dirPath, 0755);
        }
        $filePath = PathUtil::path($dirPath, substr(md5($key), 2) . ".lock");
        FileUtil::write($filePath, time());
    }

    public function open($key)
    {
        $path = Config::get("framework.runtime.lock.path");
        $dirPath = PathUtil::path($path, substr(md5($key), 0, 2));
        $filePath = PathUtil::path($dirPath, substr(md5($key), 2) . ".lock");
        $fp = fopen($filePath, 'w');
        if (flock($fp, LOCK_EX)) {
            fwrite($fp, time());
            fclose($fp);
            return true;
        } else {
            fclose($fp);
            return false;
        }
    }

    public function close($key)
    {
        $path = Config::get("framework.runtime.lock.path");
        $dirPath = PathUtil::path($path, substr(md5($key), 0, 2));
        $filePath = PathUtil::path($dirPath, substr(md5($key), 2) . ".lock");
        $fp = fopen($filePath, 'w');
        flock($fp, LOCK_UN);
        fclose($fp);
        return true;
    }

    public function status($key)
    {

    }

    public function wait($key)
    {

    }

}